package com.qyhl.webtv.module_news.news.information.program;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.entity.news.SectionBean;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.ListViewUtils;
import com.qyhl.webtv.commonlib.utils.view.MyGridView;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 节目样式
 * A simple {@link Fragment} subclass.
 */
public class ProgramFragment extends BaseFragment implements ProgramContract.ProgramView {
    @BindView(R2.id.section_gv)
    MyGridView sectionGv;
    @BindView(R2.id.news_gv)
    MyGridView newsGv;
    @BindView(R2.id.news_layout)
    LinearLayout newsLayout;
    @BindView(R2.id.scrollview)
    ScrollView scrollview;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private ProgramPresenter mPresenter;

    private String menuId;

    private String type;

    private List<SectionBean> sectionBeanList;

    private List<NewsBean> newsBeanList;

    private RequestOptions options;

    private String sections;

    private Boolean hasNew;

    public void setHasNew(Boolean hasNew) {
        this.hasNew = hasNew;
    }

    public static ProgramFragment newInstance(String menuId, String type) {
        ProgramFragment programFragment = new ProgramFragment();
        programFragment.setMenuId(menuId);
        programFragment.setType(type);
        programFragment.setHasNew(true);
        return programFragment;
    }

    public static ProgramFragment newInstance(String menuId, String type, boolean hasNew) {
        ProgramFragment programFragment = new ProgramFragment();
        programFragment.setMenuId(menuId);
        programFragment.setType(type);
        programFragment.setHasNew(hasNew);
        return programFragment;
    }




    private void setType(String type) {
        this.type = type;
    }

    private void setMenuId(String menuId) {
        this.menuId = menuId;
    }


    @SuppressLint("InflateParams")
    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.news_fragment_program, null);
    }

    @Override
    protected void create() {
        mPresenter = new ProgramPresenter(this);
        initView();
        mPresenter.getSection(menuId, type);
    }

    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    public void initImmersionBar() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        sectionBeanList = new ArrayList<>();

        newsBeanList = new ArrayList<>();

        //glide配置
        options = new RequestOptions()
                .placeholder(R.drawable.cover_normal_default)
                .error(R.drawable.cover_normal_default)
                .priority(Priority.HIGH)
                .optionalTransform(new GlideRoundTransform(4));

        //配置刷新
        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setEnableLoadMore(false);
        refresh.setDisableContentWhenRefresh(true);


        sectionGv.setAdapter(new CommonAdapter<SectionBean>(getActivity(), R.layout.news_item_program_section, sectionBeanList) {
            @Override
            protected void convert(ViewHolder viewHolder, SectionBean item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                ImageView cover = viewHolder.getView(R.id.cover);

                title.setText(item.getSectionName());
                Glide.with(ProgramFragment.this)
                        .load(item.getSectionCover())
                        .apply(options)
                        .into(cover);
            }
        });

        newsGv.setAdapter(new CommonAdapter<NewsBean>(getActivity(), R.layout.news_item_program_news, newsBeanList) {
            @Override
            protected void convert(ViewHolder viewHolder, NewsBean item, int position) {
                TextView title = viewHolder.getView(R.id.title);
                ImageView cover = viewHolder.getView(R.id.cover);

                title.setText(item.getTitle());
                Glide.with(getActivity())
                        .load(item.getLogo())
                        .apply(options)
                        .into(cover);
            }
        });

        scrollview.scrollTo(0, 0);
    }

    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(refreshlayout -> mPresenter.getSection(menuId, type));

        //重新加载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("点击重试~~");
            mPresenter.getSection(menuId, type);
        });

        sectionGv.setOnItemClickListener((parent, view, position, id) -> {
            if (sectionBeanList.get(position).getMenuType() == 6
                    ||sectionBeanList.get(position).getMenuType() == 7) {
                Bundle bundle = new Bundle();
                bundle.putString("title", sectionBeanList.get(position).getSectionName());
                bundle.putString("catalogId", sectionBeanList.get(position).getSectionId() + "");
                bundle.putInt("type",sectionBeanList.get(position).getMenuType());
                RouterManager.router(ARouterPathConstant.NB_LIST, bundle);
            } else {
                Bundle bundle = new Bundle();
                bundle.putString("title", sectionBeanList.get(position).getSectionName());
                bundle.putString("id", sectionBeanList.get(position).getSectionId() + "");
                RouterManager.router(ARouterPathConstant.NEWS_LIST, bundle);
            }
        });

        newsGv.setOnItemClickListener((parent, view, position, id) -> {
            NewsBean bean = newsBeanList.get(position);
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    style = bean.getCommonStyle();
                    break;
                case "2"://图片新闻
                    type = "2";
                    if (bean.getImagess().size() == 1) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() == 2) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        hasPicture = true;
                    } else if (bean.getImagess().size() >= 3) {
                        pOne = bean.getImagess().get(0).getImageUrlString();
                        pTwo = bean.getImagess().get(1).getImageUrlString();
                        pThree = bean.getImagess().get(2).getImageUrlString();
                        hasPicture = true;
                    } else {
                        hasPicture = false;
                    }
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            ItemSkipUtils.getInstance().itemSkip(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, StringUtils.isEmpty(bean.getHitCount()) ? 0 : Integer.parseInt(bean.getHitCount()),
                    bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype()), getContext());
        });


    }

    @Override
    public void setSection(List<SectionBean> beanList) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        sectionBeanList.clear();
        sectionBeanList.addAll(beanList);

        int index = 0;
        if (sectionBeanList.size() > 0) {
            index = 0;
        } else if (sectionBeanList.size() % 2 == 0) {
            index = sectionBeanList.size() / 2;
        } else {
            index = sectionBeanList.size() / 2 + 1;
        }
        ListViewUtils.calGridViewWidthAndHeigh(2, sectionGv, index * 40);

        for (int i = 0; i < sectionBeanList.size(); i++) {
            if (sectionBeanList.size() == 1) {
                sections = sectionBeanList.get(i).getSectionId() + ",";
            } else {
                if (i == 0) {
                    sections = String.valueOf(sectionBeanList.get(i).getSectionId());
                } else {
                    sections = sections + "," + sectionBeanList.get(i).getSectionId();
                }
            }
        }

        if(hasNew){
            if (StringUtils.isNotEmpty(sections)) {
                mPresenter.getHotNews(sections);
            } else {
                newsLayout.setVisibility(View.GONE);
            }
        }else{
            newsLayout.setVisibility(View.GONE);
        }

    }

    @Override
    public void setNews(List<NewsBean> beanList) {
        newsLayout.setVisibility(View.VISIBLE);
        newsBeanList.clear();
        newsBeanList.addAll(beanList);

        int index = 0;
        if (newsBeanList.size() > 0) {
            index = 0;
        } else if (newsBeanList.size() % 2 == 0) {
            index = newsBeanList.size() / 2;
        } else {
            index = newsBeanList.size() / 2 + 1;
        }
        ListViewUtils.calGridViewWidthAndHeigh(2, newsGv, index * 40);


    }

    @Override
    public void newsError() {
        newsLayout.setVisibility(View.GONE);
    }

    @Override
    public void setEmpty(String msg) {
        refresh.finishRefresh();
        loadMask.setEmptyText(msg);
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setErrorText(msg);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("节目");
        MobclickAgent.onResume(getActivity());
    }


    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("节目");
        MobclickAgent.onPause(getActivity());
    }
}
